<template>
  <div class="form-container">
    <h1>任务明细</h1>
    <el-form :model="row" :rules="taskFormRules" ref="taskFormRules" label-width="120px"
             style="margin-top: 30px;padding: 15px;">
      <el-form-item label="任务名称" prop="taskName">
        <el-input :disabled="!editable" v-model="row.taskName"></el-input>
      </el-form-item>
      <el-form-item label="任务明细" prop="taskDesc">
        <el-input :disabled="!editable" :rows="3" type="textarea" v-model="row.taskDesc"></el-input>
      </el-form-item>
      <el-form-item label="任务报酬" prop="salary">
        <el-input :disabled="!editable" v-model="row.salary"></el-input>
      </el-form-item>
      <el-form-item label="任务等级" prop="level">
        <el-input :disabled="!editable" v-model="row.level"></el-input>
      </el-form-item>
      <el-form-item label="接收人" prop="receiver">
        <el-input disabled v-model="row.receiver"></el-input>
      </el-form-item>
      <el-form-item label="是否完成" prop="finished">
        <template #default="scope">
          <el-select :disabled="!editable" @change="changeFinishState()" v-model="row.finished">
            <el-option v-for="item in finishOption" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </template>
      </el-form-item>
      <el-form-item label="任务截止时间" prop="deadline">
        <el-date-picker
            :disabled="!editable"
            v-model="row.deadline"
            type="date"
            placeholder="选择截止日期"
            :disabled-date="disabledDeadDate"
            :shortcuts="shortcuts"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD 23:59:59"
            @change="setExpried()"
        />
      </el-form-item>

      <el-form-item label="任务过期时间" prop="expired">
        <el-date-picker
            :disabled="!editable"
            v-model="row.expired"
            type="date"
            placeholder="选择过期日期"
            :disabled-date="disabledExpiredDate"
            :shortcuts="shortcuts"
            format="YYYY-MM-DD"
        />
      </el-form-item>

      <div style="margin-top: 20px;margin-bottom: 20px;">
        <el-button type="danger" @click="clearEdit">取消操作</el-button>
        <el-button :disabled="!editable" type="primary" @click="saveTaskData('taskFormRules')">修改任务信息</el-button>
        <el-button :disabled="editable" v-if="showReceive && !editable" type="success" @click="acceptTask()">接收任务
        </el-button>
        <el-button :disabled="editable" v-if="isfinish && !editable" type="success"
                   @click="submitTask('taskFormRules')">完成任务
        </el-button>
      </div>
    </el-form>
    <div style="margin-bottom: 50px;">
      <el-button v-if="!editable" type="primary" @click="showDialogBox=true">联系任务发布者</el-button>
      <el-button v-else type="primary" @click="showDialogBox=true">联系任务接收者</el-button>
    </div>
    <el-dialog :title="editable?'联系任务接收者':'联系任务发布者'" v-model="showDialogBox" width="30%" style="padding: 8px 15px;"
               @close="closeDialog">
      <el-form :model="dialogDetail" :rules="dialogDetailRules" ref="dialogDetailRules" label-width="120px">
        <el-form-item label="请输入消息" prop="beanName">
          <el-input placeholder="请输入消息..." type="textarea" :rows="5" v-model="dialogDetail.message"></el-input>
        </el-form-item>
      </el-form>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="sendMessage('dialogDetailRules')">确定</el-button>
    </el-dialog>
  </div>
</template>

<script>
import store from '@/store/index';
import {ElMessage} from 'element-plus';
import {editTask, expiredTask, acceptTask, submitTask} from '@/api/task.js';
import {sendMessage} from "@/api/conversation";

export default {
  data() {
    return {
      row: '',
      showReceive: false,
      editable: false,
      isfinish: false,

      showDialogBox: false,
      dialogDetail: [],
      dialogDetailRules: {
        message: {required: true, message: "请输入会话内容", trigger: 'blur'}
      },

      loginUser: '',

      finishOption: [{value: '1', label: '未完成'}, {value: '0', label: '已完成'}],

      taskFormRules: {
        taskName: [{required: true, message: '请输入任务名称', trigger: 'blur'}],
        taskDesc: [{required: true, message: '请输入任务明细', trigger: 'blur'}],
        salary: [
          {required: true, message: '仅能输入整数', pattern: /^[0-9]+$/, trigger: 'blur'},
          {required: true, message: '请输入任务报酬', trigger: 'blur'},
          {required: true, max: 10, trigger: 'blur', message: '最长仅能为十位'}
        ],
        level: [
          {required: true, message: '仅能输入数字', pattern: /^[0-9]+$/, trigger: 'blur'},
          {required: true, message: '请输入任务级别', trigger: 'blur'},
          {required: true, max: 1, trigger: 'blur', message: '任务等级不超过10级'}
        ],
        deadline: [{required: true, message: '请输入任务截止时间', trigger: 'blur'}],
        expired: [{required: true, message: '请输入任务过期时间', trigger: 'blur'}]
      },
      shortcuts: [
        {
          text: '今天',
          value: new Date()
        },
        {
          text: '7天后',
          value: () => {
            const date = new Date();
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 7);
            return date;
          }
        },
        {
          text: '30天后',
          value: () => {
            const date = new Date();
            date.setTime(date.getTime() + 3600 * 1000 * 24 * 30);
            return date;
          }
        }
      ]
    };
  },
  methods: {
    acceptTask() {
      const id = this.row.id;
      if (this.row.publisher == this.loginUser.id) {
        ElMessage.error('不可接受自己发布的任务！');
      } else {
        const task = {id: id};
        acceptTask(task).then(resp => {
          const taskId = resp.data.task.id;
          ElMessage.success('任务:' + taskId + '已被您成功接收，将为您返回上一页');
          setTimeout(() => {
            this.$router.go(-1);
          }, 1000);
        });
      }
    },
    clearEdit() {
      //清空表单默认值
      this.row = [];
      this.checkFlag = 0;
      ElMessage.error('数据已刷新，即将为您返回上一页');
      setTimeout(() => {
        this.$router.go(-1);
      }, 1500);
    },
    disabledDeadDate(time) {
      // 禁止选择今天以前的时间
      return time.getTime() < Date.now() - 8.64e7 || time.getTime() > Date.now() + 3600 * 1000 * 24 * 30;
    },
    disabledExpiredDate(time) {
      if (this.row.deadline) {
        this.checkFlag = 1;
        const deadline = new Date(this.row.deadline);
        return time.getTime() < deadline.getTime() - 8.64e7 || time.getTime() > deadline.getTime() + 3600 * 1000 * 24 * 30;
      } else if (!this.row.deadline && this.row.expired && this.checkFlag == '0') {
        ElMessage.error('请先选择截止日期');
        this.row.expired = '';
      }
    },
    setExpried() {
      var date = new Date();
      if (this.row.deadline) {
        const deadline = new Date(this.row.deadline);
        date.setTime(deadline.getTime() + 3600 * 1000 * 24 * 7);
        this.row.expired = date;
      } else {
        this.row.expired = '';
      }
    },
    changeFinishState() {
      ElMessage.success('已修改，修改后请重新提交数据');
    },
    saveTaskData(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$confirm('此操作将修改该任务, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })

              .then(() => {
                const expiredTime = new Date(this.row.expired);
                const param = {
                  id: this.row.id,
                  taskName: this.row.taskName,
                  taskDesc: this.row.taskDesc,
                  receiver: this.row.receiver,
                  salary: this.row.salary,
                  level: this.row.level,
                  deadline: this.row.deadline,
                  finished: this.row.finished,
                  expired: expiredTime.getTime()
                };
                editTask(param).then(resp => {
                  if (resp.success) {
                    this.$message({
                      type: 'success',
                      message: '修改成功，将为您返回上一页'
                    });
                    setTimeout(() => {
                      this.$router.go(-1);
                    }, 1500);
                  } else {
                    this.$message({
                      type: 'error',
                      message: '修改失败！' + resp.message
                    });
                  }
                });
              })
              .catch(ex => {
                this.$message({
                  type: 'error',
                  message: '修改失败！' + ex
                });
              });
        } else {
          console.log('验证失败');
          return false;
        }
      });
    },
    submitTask(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$confirm('此操作将提交任务, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const data = {
              id: this.row.id,
              finished: '0'
            };
            submitTask(data).then(resp => {
              if (resp.success) {
                this.$message({
                  type: 'success',
                  message: '修改成功，将为您返回上一页'
                });
                setTimeout(() => {
                  this.$router.go(-1);
                }, 1500);
              } else {
                this.$message({
                  type: 'error',
                  message: '修改失败！' + resp.message
                });
              }
            });
          });
        }
      });
    },
    closeDialog() {
      this.showDialogBox = false;
      ElMessage.success("已关闭对话框")
    },
    sendMessage() {
      const data = {}
      if (this.editable) {
        if (this.row.receiver == '' || this.row.receiver == undefined || this.row.receiver == null) {
          ElMessage.error("该任务暂无接收人")
          return
        }
        data.toUser=this.row.receiver
      } else {
        data.toUser=this.row.publisher
      }
      data.content= this.dialogDetail.message
      // console.log(data)
      sendMessage(data).then(resp => {
        if (resp.success) {
          ElMessage.success("消息已发送成功")
          this.showDialogBox = false
          this.dialogDetail = []
        }
      })


    },
    initData() {
      const loginUser = JSON.parse(window.sessionStorage.getItem('user'));
      this.loginUser = loginUser;
      this.row = store.state.data;
      const isFinish = this.row.finished;
      //任务未被接收
      if (!this.row.receiver) {

        this.showReceive = true;

      }
      if (this.row.receiver == loginUser.id && isFinish != '0') {

        //接收人等于登录人,且任务未完成,允许完成任务
        this.isfinish = true;

      }
      //禁止自己接收自己的任务
      if (this.row.publisher == loginUser.id && isFinish != '0') {
        this.editable = true;

      }

      if (this.row.length == 0) {
        ElMessage.error('数据已刷新，即将为您返回上一页');
        setTimeout(() => {
          this.$router.go(-1);
        }, 1500);
      }
    }
  },
  created() {
  },
  mounted() {
    this.initData();
  }
};
</script>

<style>
.taskDetail {
  height: auto;
  width: 60%;
  background-color: #e6f7ff;
  border-radius: 4px;
  padding: 20px;
  box-sizing: border-box;
  text-align: center;
  color: #1890ff;
}

.form-container {
  border: 1px solid #ccc;
  padding: 10px;
  border: 1px solid #ccc;
  padding: 10px;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
  margin: 25px auto 0;
  max-width: 35%;
}
</style>
